package com.basic.business.rpaServer;


import com.basic.business.common.constants.Constants;
import com.basic.business.common.enums.PstStatus;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.common.utils.FileUtils;
import com.basic.business.common.utils.StringUtils;
import com.basic.business.common.utils.UserUtils;
import com.basic.business.log.service.ITOrdersLogService;
import com.basic.business.memoType.MemoTypeUtils;
import com.basic.business.order.domain.TOrdersMain;
import com.basic.business.order.domain.TOrdersStatus;
import com.basic.business.order.service.ITOrdersStatusService;
import com.basic.business.redis.domain.TOrdersMainRedis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * 自动打包服务优化版
 */
@Slf4j
@Component
public class RPAServer {

    @Resource
    private HandleWaitAudit handleWaitAudit;

    @Resource
    private ITOrdersLogService logService;

    @Resource
    private ITOrdersStatusService statusService;

    /**
     * 入口方法
     */
    public void init(List<TOrdersMain> mains){
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch latch = new CountDownLatch(mains.size());

        try {
            // 提交所有任务到线程池
            for (TOrdersMain main : mains) {
                executorService.submit(() -> {
                    try {
                        handleOrder(main);
                    } finally {
                        latch.countDown(); // 每个任务完成后减少计数
                    }
                });
            }
            // 等待所有任务完成
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 重新设置中断状态
            log.error("任务等待过程中发生中断异常", e);
        } finally {
            executorService.shutdown(); // 关闭线程池
        }
    }

    public void handleOrder(TOrdersMain main){
        // 获取主订单状态
        String sysStatus = main.getSysStatus();

        // 主订单状态：CLOSED（交易关闭）、CANCEL（交易取消）、FINISHED（交易完成）的，直接删除打包文件，删除Redis中的信息
        if (StringUtils.containsAny(sysStatus, "CLOSED", "CANCEL", "FINISHED")) {
            deleteRedisAndFile(main);
        }

        // 主订单状态：WAIT_AUDIT（待审核）
        if (StringUtils.equals(sysStatus, "WAIT_AUDIT")) {
            handleWaitAudit.init(main);
        }

        handleMemoType(main);

    }

    /**
     * 删除Redis中的订单和打包文件
     */
    public void deleteRedisAndFile(TOrdersMain main) {
        long mainSid = main.getSid();

        TOrdersStatus status = TOrdersStatus.createTOrdersStatus(main);
        try {
            // 获取Redis中的订单
            TOrdersMainRedis mainRedis = RedisCacheUtils.getCacheObject(Constants.ORDERS_REDIS_KEY + mainSid);
            if (mainRedis != null) {
                mainRedis.getDetailList().forEach(detail -> {
                    // 获取smb路径
                    String smbPath = detail.getSmbPath();
                    if (StringUtils.isNotBlank(smbPath)) {
                        // 删除打包文件 按逗号分割路径并逐个删除
                        Arrays.stream(smbPath.split(","))
                                .filter(path -> StringUtils.isNotBlank(path.trim()))
                                .forEach(path -> FileUtils.deleteFromSmb(path, main.getShortId()));
                    }
                });

                // 删除Redis中的订单
                RedisCacheUtils.deleteObject(Constants.ORDERS_REDIS_KEY + mainSid);
                // 记录日志
                logService.insert(mainSid, mainSid, "执行【交易关闭、交易取消、交易完成】策略成功；");
            }
        }catch (Exception e) {
            // 更新主订单自动处理状态为【人工处理】
            status.setOrderStatus(PstStatus.MANUAL.name());
            statusService.insertPst(status);
            // 记录日志
            logService.insert(mainSid, mainSid, "执行【交易关闭、交易取消、交易完成】策略失败；");
            log.error("执行【交易关闭、交易取消、交易完成】策略失败；系统单号：{}；原因：", mainSid, e);
        }

    }

    /**
     * 处理备注中的整理人和备注类型
     */
    public void handleMemoType(TOrdersMain main) {

        boolean isDetailsContains = main.getMergeList().stream().anyMatch(detail -> StringUtils.contains(detail.getSellerMemo(), "【人工处理】"));
        if (isDetailsContains) {
            TOrdersStatus status = TOrdersStatus.createTOrdersStatus(main);

            String memoValues = MemoTypeUtils.getMemoType(main.getMergeList());
            if (StringUtils.isNotEmpty(memoValues)) {
                status.setMemoValue(memoValues);
                status.setOrderStatus("MANUAL_SERVICE"); // 人工-客服整理
                status.setAllocateType("1"); // 0 单号分配  1自动分配
            } else {
                status.setOrderStatus(PstStatus.MANUAL.name());
                status.setAllocateType("0"); // 0 单号分配  1自动分配
            }
            // 获取备注中的整理人
            String customers = UserUtils.extractUserId(main.getMergeList());
            if (StringUtils.isNotEmpty(customers)) {
                status.setCustomer(customers);
            }
            statusService.updatePst(status);
        }


    }

}